#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mem_manage.h"
#include "write_shmem.h"
#include <assert.h>
//typedef unsigned char u_char;
//typedef unsigned int u_int;
typedef unsigned short int s_int;

int main()
{
    
    int j = 0;
    int i = 0;
    int semid;
    int readsize;
    void *smptr;
    int mailsize = 0;
    u_char *mailtmpsave = NULL;
    int sublen = 0;
    int textlen = 0;
    mailinfo * mailhead = NULL;
    s_int * siptr = NULL;
    char * subptr = NULL;
    char * textptr = NULL;

    semid=getSem(S_SEM_NAME,M_SEM_ID,GET);
    mem_start=getMem(S_MEM_NAME,M_MEM_ID,TOTAL_LEN,GET);
    smptr=mem_start;

    mailhead = (mailinfo *)malloc(sizeof(mailinfo));
    printf("This is read\n");

readhead:
    assert(mailhead != NULL);
    while((readsize=my_read(&smptr,mailhead,semid))==READ_FAILED)
    {
	printf("read wait1\n");
	sleep(1);
    }
    if(readsize!=0)
    {
        printf("\n----------------Mail %d is coming----------------\n",++j);
        printf("Readsize: %d\n",readsize);
        printf("sortip %u| desip %u\n",mailhead->sorip,mailhead->desip);
        printf("maisize is %u\n",mailhead->mailsize);
        mailsize =(int)mailhead->mailsize;
        printf("\n-----------------------------------------------------\n");
    }
    else
        goto readhead;

    printf("-----------------MailContent----------------------------\n");
    mailtmpsave = (u_char *)malloc(sizeof(char) * mailsize+1);
    memset(mailtmpsave, 0, sizeof(char) * mailsize+1);

readtxt:
    while((readsize=my_read(&smptr,mailtmpsave,semid))==READ_FAILED)
    {
        printf("read wait2\n");
        sleep(1);
    }
    if(readsize!=0)
    {
        mailtmpsave[mailsize] = '\0';
        printf("Readsize: %d\n",readsize);
        siptr = (s_int *)mailtmpsave;
        sublen = *siptr;
        printf("sublen is %d\n",sublen);
        siptr = (s_int *)(mailtmpsave+2);
        textlen = *siptr;
        printf("textlen is %d\n",textlen);
        subptr = (char *)malloc( sizeof(char ) * sublen);
        assert(subptr != NULL);
        strncpy(subptr,mailtmpsave+4,sublen-1);
        subptr[sublen-1] = '\0';
        printf("subject is %s\n",subptr);
        textptr = (char *)malloc( sizeof(char ) * textlen);
	assert(textptr != NULL);
        strncpy(textptr,mailtmpsave+4+sublen,textlen-1);
        textptr[textlen-1] = '\0';
        printf("textptr is %s\n",textptr);
        printf("------------------Mail sub is over !----------------\n",j);

        free(subptr);
        free(textptr);
        free(mailtmpsave);
    }
    else
    goto readtxt;

    goto readhead;
    return 0;
}
